package com.taojiazheng.interceptor;

import com.taojiazheng.common.ApplicationException;
import com.taojiazheng.common.annotations.VisitorAccessible;
import com.taojiazheng.entity.User;
import com.taojiazheng.service.user.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 赵成林
 * @date 2017/11/22 19:42
 */


public class UserAccessInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o) throws Exception {
        // 前后端分离，解决跨域
        response.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Accept,X-Requested-With,token");
        String token = httpServletRequest.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            // 无效的token
            if (!isUsefulToken(token)) {
                throw new ApplicationException(202, "无效的token，请重新登录");
            }

        } else {
            if (o instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) o;
                VisitorAccessible visitorAccessible = handlerMethod.getMethodAnnotation(VisitorAccessible.class);
                if (visitorAccessible != null) {
                    return true;
                }
                if ((!handlerMethod.getMethod().getName().toUpperCase().equals("LOGIN")) && (!handlerMethod.getMethod().getName().toUpperCase().equals("REGISTER"))) {
                    throw new ApplicationException(201, "请先登录，再去访问");
                }
            }
        }


        return true;


    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    private boolean isUsefulToken(String token) {
        User user = userService.getUserByToken(token);
        if (user == null) {
            return false;
        }
        return true;
    }
}
